package com.woniuxy.shior;

import org.apache.shiro.mgt.SessionStorageEvaluator;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.DefaultWebSessionStorageEvaluator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    /**
     *  配置securityManager，因为我们要自定义JWT方式进行认证！
     *  把自定义域交给securityManager来进行管理和使用！
     * @param mrRealm
     * @return
     */
    @Bean
    public DefaultWebSecurityManager securityManager(MyRealm mrRealm){
        mrRealm.setAuthenticationTokenClass(MyJWt.class);
        return new DefaultWebSecurityManager(mrRealm);
    }

    /**
     *  配置过滤器工厂，使用我们写的JWTFilter生效！以及过滤条件和拦截url配置！
     * @param defaultWebSecurityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
    Map<String, Filter> filters = new HashMap<>();
    filters.put("JWT",new JWTFilter());
    shiroFilterFactoryBean.setFilters(filters);
    Map<String,String> filterMap= new HashMap<>();
    filterMap.put("/**","JWT");
    filterMap.put("/rbacManager/**","authc");
    //anon 是匿名访问 除此之外还有个常用的 authc 需要认证！
    filterMap.put("/login","anon");
    filterMap.put("/401","anon");
    shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
}

    /**
     * 禁用session, 不保存用户登录状态。保证每次请求都重新认证。
     * 需要注意的是，如果用户代码里调用Subject.getSession()还是可以用session
     * @return
     */
    @Bean
    protected SessionStorageEvaluator sessionStorageEvaluator(){
        DefaultWebSessionStorageEvaluator defaultWebSessionStorageEvaluator= new DefaultWebSessionStorageEvaluator();
        defaultWebSessionStorageEvaluator.setSessionStorageEnabled(false);
        return defaultWebSessionStorageEvaluator;
}
@Bean
/**
 *  开启shiro注解支持
 */
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
}

    /**
     * 管理Subject主体对象,生命周期的组件,用户只是打印下生产销毁日志什么的,请参考spring中bean的生命周期
     * @return
     */
    @Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){
        return new LifecycleBeanPostProcessor();
}
}
